const db = uniCloud.database();
const UniSubscribemsg = require('uni-subscribemsg');

exports.main = async (event, context) => {
  const now = new Date();
  const appointmentCol = db.collection('appoint_schedule');
  const userCol = db.collection('uni-id-users');

  try {
    const { data } = await appointmentCol.where({
      hasSent: false,
      hasSubscribed: true
    }).get();

    console.log(`✅ 开始检查预约提醒，共有 ${data.length} 条候选记录`);

    const reminders = data.map(async (record, index) => {
      try {
        const { appointedSlot, day, uid, consultant } = record;

        // 🛠️ 输出调试字段，便于排查字段缺失问题
        console.log(`📌 第 ${index + 1} 条记录字段检查:`, {
          appointedSlot,
          day,
          uid,
          consultant
        });

        if (!appointedSlot || !day || !uid) {
          console.warn(`⚠️ 第 ${index + 1} 条记录字段缺失，跳过，_id: ${record._id}`);
          return;
        }

        // 查找 openid
        let userResult;
        try {
          userResult = await userCol.doc(uid).get();
        } catch (e) {
          console.error(`❌ 获取用户信息失败，uid: ${uid}`, e);
          return;
        }

        const user = userResult.data[0];
        const openid = user?.wx_openid?.mp;

        if (!openid) {
          console.warn(`⚠️ 用户 ${uid} 未绑定 openid，跳过`);
          return;
        }

        // 时间计算
        const startTimeStr = appointedSlot.split('-')[0];
        const [hour, minute] = startTimeStr.split(':').map(Number);
        const appointDate = new Date(day);
        const appointStart = new Date(
          appointDate.getFullYear(),
          appointDate.getMonth(),
          appointDate.getDate(),
          hour,
          minute
        );
        const diffMinutes = (appointStart - now) / 1000 / 60;

        if (diffMinutes <= 60 && diffMinutes > 0) {
          const uniSubscribemsg = new UniSubscribemsg({
            dcloudAppid: "__UNI__EE510EF",
            provider: "weixin-mp"
          });

          const formattedDate = `${appointDate.getFullYear()}年${appointDate.getMonth() + 1}月${appointDate.getDate()}日`;
          const finalTime = `${formattedDate} ${startTimeStr}`;

          try {
            const res = await uniSubscribemsg.sendSubscribeMessage({
              touser: openid,
              template_id: "lpbzb9GviTD0yJ0woys9ijVx3mp2WIDwQcQYX-FPa64",
              page: "pages/index/index",
              miniprogram_state: "formal",
              lang: "zh_CN",
              data: {
                time2: { value: finalTime },
                thing28: { value: consultant || "咨询师" }
              }
            });

            if (res.errCode === 0) {
              try {
                await appointmentCol.doc(record._id).update({ hasSent: true });
                console.log(`📬 已成功发送提醒消息并标记为已发送，用户: ${uid}, 时间: ${finalTime}`);
              } catch (e) {
                console.error(`❌ 消息已发，但更新记录失败，_id: ${record._id}`, e);
              }
            } else {
              console.error(`❌ 消息发送失败，微信返回错误:`, res);
            }
          } catch (err) {
            console.error(`❌ 发送订阅消息失败，用户: ${uid}, openid: ${openid}`, err);
          }
        } else {
          console.log(`⏳ 时间未到，用户: ${uid}, 剩余分钟: ${Math.round(diffMinutes)}`);
        }
      } catch (err) {
        console.error(`❌ 处理第 ${index + 1} 条预约记录时出错，_id: ${record._id}`, err);
      }
    });

    await Promise.all(reminders);

    console.log("✅ 所有预约消息处理完毕");
    return { code: 0, msg: '检查完成，消息已处理' };
  } catch (err) {
    console.error('❌ 定时提醒出错:', err);
    return { code: -1, msg: '提醒失败', err };
  }
};
